package com.xxd.dfs.namenode;

import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.LinkedBlockingQueue;

/**
 * @author: XiaoDong.Xie
 * @create: 2020-08-21 12:16
 * @description: 拉取edit queue的队列缓冲
 */
public class EditLogCache {

    private static EditLogCache instance = new EditLogCache();

    private LinkedBlockingQueue<EditLog> queue = new LinkedBlockingQueue<>(16000);

    public static EditLogCache getInstance() {
        return instance;
    }

    private EditLogCache() {

    }

    public int size() {
        return queue.size();
    }

    public void offer(EditLog editLog) {
        queue.offer(editLog);
    }

    /**
     * 本次拉取的数量
     *
     * @return
     */
    private int fetchSize() {
        if (queue.size() > 1000) {
            return 1000;
        } else if (queue.size() > 500) {
            return 500;
        } else if (queue.size() > 100) {
            return 100;
        } else if (queue.size() > 50) {
            return 50;
        } else {
            return queue.size();
        }
    }


    public List<EditLog> fetchEditLogs() {
        List<EditLog> editLogs = new ArrayList<>();

        int size = fetchSize();
        for (int i = 0; i < size; i++) {
            editLogs.add(queue.poll());
        }
        return editLogs;
    }
}
